import { Module } from "vuex"
import {
  userMsgUpdate,
  userMsgGet,
  login,
  accountUserLogin,
  getLoginId,
  uniformLogin,
  getTenantId
} from "@/api/modules/user"; // login,
import { setSignRule } from "@/api/modules/integral";
import { getCarsList } from "@/api/modules/shopCar";
import storage from "@/utils/storage";
import isEqual from "lodash/isEqual";

interface InfoExtends {
  clockNum: objectdata;
  communityId: string;
  consumeNum: number;
  integral: number;
  integralTotal: objectdata;
  isBlacklist: number;
  lastDealTime: objectdata;
  lastLoginTime: string;
  oneselfActivityAssociation: objectdata;
  assembleActivityAreaAssociation: objectdata;
  shippingPointInfoVo: objectdata;
  shopId: string;
}
interface IUser {
  tenantId: string;
  token: string;
  couponType: boolean;
  infoExtends: InfoExtends;
  shopUserId: string;
  transData: any;
}

type objectdata = {
  [key:string]: string | number | boolean | objectdata | any[]
}

const module: Module<Record<string, any>, Record<string, any>> = {
  namespaced: true,
  state: {
    /** 用户信息 */
    userInfo:storage.get("getLoginData") ||  { tenantId: "", token: "", couponType: true,infoExtends:{
      memberInfo:[{
        id: null,
        memberCardInfoId: null,
        memberExpireTime: null,
        rankCode: null,
        rankName: null,
        rebateBonus: 0,
        state: 0,
        status: 2,
        supplyAndRebateBonus: 0,
        supplyBonus: 0,
        userId: "-1"
      }]
    } } ,

    /** 自定义用户信息 */
    userInfoTem: null,

    /** 自定义用户信息 */
    goodsNumber: 0,


  },
  getters: {
    
  },
  mutations: {
    /**
     * @description 设置用户信息
     * @param data 用户信息
     */
    setUserInfo(state, data: IUser) {
      state.userInfo = data
    },

    /**
     * @description 设置全局购物车数量
     * @param data 购物车数量
     */
    setGoodsNumber(state,data:number){
      state.goodsNumber = data
    }
  },
  actions: {
    //获取code
    getCode(context){
      return new Promise((resolve) => {
        //获取微信小程序 OPENID
        uni.login({
          success: (login_res) => {
            if(login_res.errMsg == 'login:ok'){
              resolve(login_res);
              const userInfo=context.state.userInfo
              userInfo.code=login_res.code
              context.commit('setUserInfo',userInfo)
            }
          },
          fail: (err) => {
            console.log(err)
          }
        });
      });
    },

    /** 微信登陆方法
     * @param type 是否清除登录缓存，1是，0否
     */
    async login(context,info) {
      try{
        if (info.type === 1) {
          storage.remove("getLoginData");
        }
        let userInfo = context.state.userInfo
        // const {code} = await context.dispatch('getCode')
        const code =context.state.userInfo.code
        const { sessionKey } = await login(code);
        const {iv,encryptedData} = info.detail
        const loginId= await getLoginId({sessionKey,iv,encryptedData})
        const result=await uniformLogin(loginId)
        userInfo.token =result.token.token;
        const user = await userMsgGet({ infoLevel: 2 });
        userInfo = Object.assign({}, userInfo, user, {
          couponType: true,
          sessionKey,
        });
        const transData = {
          goodData: {},
          shopUserId: userInfo.shopUserId,
          communityId: userInfo.infoExtends.communityId,
        } as objectdata;
        // if (user.whetherAuthorization) {
        //   userMsgUpdate(userInfo);
        // }
        userInfo.transData = transData;
        userInfo.infoExtends = user.infoExtends
        const res = userInfo;
        if (res && !isEqual(res, storage.get("getLoginData"))) {
          storage.set("getLoginData", res, 3 * 24 * 60 * 60 * 1000);
        }
        context.commit('setUserInfo', userInfo)
        accountUserLogin({});
      }catch{
        uni.login({
          success: (login_res) => {
            if(login_res.errMsg == 'login:ok'){
              uni.showToast({
                icon:"none",
                title:"授权失败"
              })
              const userInfo=context.state.userInfo
              userInfo.code=login_res.code
              context.commit('setUserInfo',userInfo)
            }
          },
          fail: () => {
            uni.showToast({
              icon:"none",
              title:"重新获取code失败"
            })
          }
        });
      }
    },

    /**
     * 获取购物车数量
     */
    async getShopCarNum(context) {
      const res = await getCarsList();
      const useList = [] as any
      const noList = [] as any
      let goodsNumber = 0
      if (!res) {
        goodsNumber = 0;
      }else{
        const list = res;
        list.forEach((item: { skuList: number[]; skuStocks: {id:number,stock:number}[]; status: number; deleted: number; skuId: number; activityEndTime: string; activityStatus: string; }) => {
          item.skuList = [];
          item.skuStocks.forEach(v => {
            item.skuList.push(v.id);
          });
          const type = item.skuStocks.every(v => {
            return v.stock === 0;
          });
          item.status = type ? 2 : item.status;
          if (item.deleted === 1) {
            item.status = 2;
          }
          item.status = item.skuList.indexOf(item.skuId) === -1 ? 0 : item.status;
          if (item.activityEndTime) {
            item.status =
              item.activityStatus === "1" || item.activityStatus === "0" ? 1 : 0;
          }
          if (item.status === 1) {
            useList.push(item);
          } else {
            noList.push(item);
          }
        });
        goodsNumber = useList.reduce((preVal: number, item: { goodsNumber: number; }) => {
          return preVal + item.goodsNumber;
        }, 0);
      }
      context.commit('setGoodsNumber',goodsNumber)
    },

    /**
     * @description 更新用户数据
     * @param userInfo 用户数据信息
     */
    async updateUser(context,userInfo:IUser) {
      await setSignRule({});
      await userMsgUpdate(userInfo);
      await context.dispatch('login');
    },

    /**
     * 获取第三方tenantId
     */
    async getTenId(context) {
      const accountInfo = uni.getAccountInfoSync().miniProgram.appId;
      console.log('accountInfo',accountInfo); // 小程序 appId
      const extConfig = uni.getExtConfigSync ? uni.getExtConfigSync() : {}
      console.log('extConfig',extConfig)
      const tenantId = await getTenantId({appId:accountInfo})
      console.log('tenantId',tenantId);
      
      // const tenantId = uni.getExtConfigSync ? uni.getExtConfigSync().tenantId : process.env.VUE_APP_TENAN_ID
      const userInfo = {
        ...context.state.userInfo,
        tenantId: tenantId,
      }
      context.commit('setUserInfo', userInfo);
    },
        /**
     * 删除token
     */
    async deleteToken(context){
      storage.remove("getLoginData");
      const userInfo={ tenantId: "", token: "", couponType: true,infoExtends:{
        memberInfo:[{
          id: null,
          memberCardInfoId: null,
          memberExpireTime: null,
          rankCode: null,
          rankName: null,
          rebateBonus: 0,
          state: 0,
          status: 0,
          supplyAndRebateBonus: 0,
          supplyBonus: 0,
          userId: "-1"
        }]
      } } 
      context.commit('setUserInfo', userInfo);
    }
  }
}

export default module;
